#!/bin/bash

# 设置颜色
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 检查环境参数
if [ -z "$1" ]; then
    echo -e "${RED}Please specify environment (production/staging)${NC}"
    exit 1
fi

ENV=$1

echo -e "${GREEN}Starting deployment for ${ENV} environment...${NC}"

# 检查必要文件
if [ ! -f ".env.${ENV}" ]; then
    echo -e "${RED}.env.${ENV} file not found${NC}"
    exit 1
fi

# 构建应用
echo -e "${YELLOW}Building application...${NC}"
npm run build

# 停止现有容器
echo -e "${YELLOW}Stopping existing containers...${NC}"
docker-compose -f docker-compose.${ENV}.yml down

# 备份数据库
if [ "$ENV" = "production" ]; then
    echo -e "${YELLOW}Backing up database...${NC}"
    ./scripts/backup-db.sh
fi

# 复制环境文件
echo -e "${YELLOW}Setting up environment...${NC}"
cp .env.${ENV} .env

# 启动新容器
echo -e "${YELLOW}Starting new containers...${NC}"
docker-compose -f docker-compose.${ENV}.yml up -d --build

# 等待服务就绪
echo -e "${YELLOW}Waiting for services to be ready...${NC}"
sleep 10

# 运行数据库迁移
echo -e "${YELLOW}Running database migrations...${NC}"
npm run db:migrate

# 清理旧镜像
echo -e "${YELLOW}Cleaning up old images...${NC}"
docker image prune -f

echo -e "${GREEN}Deployment complete!${NC}"
echo -e "${YELLOW}Please verify the application is running correctly${NC}"

# 监控日志
echo -e "${YELLOW}Showing application logs...${NC}"
docker-compose -f docker-compose.${ENV}.yml logs -f app
